<template>
	<view class="uni-column chat">
		<div v-if="pageShow">
			<view class="content" id="content" @click="hideKeyboard">
				<div id="scrollview">
					<div class="loading no-more" v-show="!isMore">
						{{ $t('没有更多了') }}
					</div>
					<message-show v-for="(item, index) in msgList" :key="index" :avatar="avatar" :message="item"></message-show>
					<view id="bottom"></view>
				</div>
			</view>
			<Emoji
				@updata-val="updataVal"
				@on-upload="onUpload"
				:input-value="inputValue"
				:isShow="showEoji"
				@send-message="getInputMessage"
				v-if="showEoji"
				@show-emoji="onShowEmoji"
			></Emoji>
			<view class="chat-footer">
				<chat-input
					:focus="focus"
					:input-value="inputValue"
					:isShow="showEoji"
					@send-message="getInputMessage"
					@updata-val="updataVal"
					@on-upload="onUpload"
					@show-emoji="onShowEmoji"
				></chat-input>
			</view>
		</div>
		<view class="goods-float" v-if="goodsFloatShow">
			<u-image
				:src="goodsInfo.thumb_url"
				class="goods-float-thumble"
				width="110"
				height="110"
				border-radius="10"
				@click="$u.route('/pagesC/goods/goodsDetails', { id: goodsInfo.id })"
			></u-image>
			<view class="goods-float-center" @click="$u.route('/pagesC/goods/goodsDetails', { id: goodsInfo.id })">
				<p class="goods-float-name">{{ goodsInfo.goods_name }}</p>
				<p class="goods-float-price">¥{{ goodsInfo.zs_shop_price }}</p>
			</view>
			<u-button size="mini" shape="circle" type="success" class="goods-float-sendBtn" @click="sendGoods(goodsInfo)">发送商品</u-button>
			<u-icon name="close" class="goods-float-close" color="#999" size="28" @click="closeGoodsFloat"></u-icon>
		</view>
		<view class="goods-float" v-if="ordersFloatShow" style="display: block">
			<view style="margin-bottom: 10rpx">订单号: {{ orderInfo.ordernumber }}</view>
			<view v-for="(item, index) in orderInfo.goodsinfo" :key="index" style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 10rpx">
				<view style="display: flex; align-items: center; margin-bottom: 10rpx">
					<u-image
						:src="item.thumb_url"
						class="goods-float-thumble"
						width="110"
						height="110"
						border-radius="10"
						@click="$u.route('/pagesC/order/orderDetails', { order_num: order_num })"
					></u-image>
					<view class="goods-float-center" @click="$u.route('/pagesC/goods/goodsDetails', { id: item.id })">
						<p class="goods-float-name">{{ item.goods_name }}</p>
						<p class="goods-float-price">¥{{ item.real_price }}</p>
					</view>
				</view>
				<view>
					<u-button size="mini" shape="circle" type="success" class="goods-float-sendBtn" style="float: right" @click="sendOrders(item)">发送订单</u-button>
					<u-icon name="close" class="goods-float-close" color="#999" size="28" @click="closeOrdersFloat"></u-icon>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import chatInput from '@/pagesB/components/im-chat/chatinput.vue';
import messageShow from '@/pagesB/components/im-chat/messageshow.vue';
import Emoji from '@/pagesB/components/im-chat/Emoji.vue';
import { parseImgStr, parseGoodsStr, parseOrdersStr } from './utils.js';
let order_num = '';

export default {
	data() {
		return {
			style: {
				pageHeight: 0,
				contentViewHeight: 0,
				footViewHeight: 110,
				mitemHeight: 0
			},
			isAnimation: false,
			scrollTop: 0,
			showEoji: false,
			focus: false,
			inputValue: '',
			pageShow: false,
			msgList: [],
			avatar: '',
			toId: '',
			toUserId: '',
			page: 1,
			isMore: true,
			isOrder: false,
			isGetMore: false,
			goodsInfo: {},
			orderInfo: {},
			goodsFloatShow: false,
			ordersFloatShow: false,
		};
	},

	components: {
		chatInput,
		messageShow,
		Emoji
	},

	onLoad(option) {
		this.$loading();
		this.toId = option.toId;
		console.log(option.toId);
		this.goodsId = option.goodsId;
		if (option.isOrder) {
			this.ordersFloatShow = true;
			this.isOrder = option.isOrder;
			order_num = option.order_num;
			this.orderId = option.orderId;
			this.getOrderInfo();
		} else {
			if (!this.goodsId) {
				this.goodsFloatShow = false;
			} else {
				this.goodsFloatShow = true;
				this.getGoodsInfo();
			}
		}
		const userInfo = JSON.parse(uni.getStorageSync('userInfo'));
		this.token = uni.getStorageSync('token');
		this.avatar = userInfo.headimgurl ? userInfo.headimgurl : this.STATICURL + `images/logo.png`;
		this.toUserId = this.toId;
		const res = uni.getSystemInfoSync();
		this.style.pageHeight = res.windowHeight;
		this.style.contentViewHeight = res.windowHeight - (uni.getSystemInfoSync().screenWidth / 750) * 100; //像素
		this.$hideLoading();
		this.pageShow = true;
	},

	onUnload() {
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 'readmsg',
				data: {
					fromid: uni.getStorageSync('token'),
					toid: this.toId
				}
			})
		});
	},

	onShow() {
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 'readmsg',
				data: {
					fromid: uni.getStorageSync('token'),
					toid: this.toId
				}
			})
		});

		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 'history',
				data: {
					fromid: uni.getStorageSync('token'),
					toid: this.toId
				}
			})
		});

		uni.onSocketMessage((res) => {
			const data = JSON.parse(res.data);
			if (data.type === 'init') {
				if (uni.getStorageSync('token') != '') {
					const client_id = data.data.client_id;
					uni.sendSocketMessage({
						data: JSON.stringify({
							type: 'bind_id',
							id: uni.getStorageSync('token'),
							client_id
						})
					});
					uni.setStorageSync('client_id', client_id);
				}
			}

			if (data.type === 'say') {
				console.log('消息say触发');
				const {
					data: receiveData = {},
					data: { message_type }
				} = data;

				if (receiveData.fromid !== uni.getStorageSync('token')) {
					receiveData.to_headimgurl = receiveData.from_headimgurl;
				}
				if (message_type === 'img') {
					receiveData.message = parseImgStr(receiveData.message);
					receiveData.width = 150;
					receiveData.height = 150;
				} else {
					receiveData.message = $utils.generateRichTextNode(receiveData.message, receiveData.message_type);
				}
				receiveData.userType = receiveData.fromid === uni.getStorageSync('token') ? 'customer' : 'home';

				if (receiveData.fromid == this.toId && receiveData.toid == uni.getStorageSync('token')) {
					this.msgList.push(receiveData);
				}
				this.$nextTick(() => {
					setTimeout(() => {
						this.scrollToBottom();
					}, 50);
				});
				var pages = getCurrentPages();
				var page = pages[pages.length - 1];
				// #ifdef APP-PLUS
				var currentWebview = page.$getAppWebview();
				if (currentWebview.__uniapp_route === 'pagesC/live/Audience') {
					uni.showToast({
						title: this.$t('您有新的消息，请到消息中心查看'),
						duration: 4000,
						icon: 'none'
					});
				}
				// #endif

				uni.vibrateLong({
					success: function () {
						console.log('success');
					}
				});
			}

			if (data.type === 'history') {
				let receiveMsg = data.data.reverse();
				this.msgList = receiveMsg.map((item) => {
					if (item.fromid !== this.token) {
						item.to_headimgurl = item.from_headimgurl;
					}
					if (item.message_type === 'img') {
						item.message = parseImgStr(item.message);
					} else if (item.message_type === 'goods') {
						item.message = parseGoodsStr(item.message);
					} else if (item.message_type === 'orders') {
						item.message = parseOrdersStr(item.message);
					} else {
						item.message = $utils.generateRichTextNode(item.message, item.message_type);
					}

					item.userType = item.fromid === uni.getStorageSync('token') ? 'customer' : 'home';

					return item;
				});

				this.$nextTick().then(() => {
					setTimeout(() => {
						this.scrollToBottom();
					}, 50);
				});
			}
		});
	},

	onBackPress() {
		uni.sendSocketMessage({
			data: JSON.stringify({
				type: 'readmsg',
				data: {
					fromid: uni.getStorageSync('token'),
					toid: this.toId
				}
			})
		});
	},

	methods: {
		getGoodsInfo() {
			this.$http
				.getGoodsInfo({
					goods_id: this.goodsId
				})
				.then((res) => {
					if (res.status == 200) {
						this.goodsInfo = res.data.goodsinfo;
						console.log(this.goodsInfo);
					}
				});
		},
		getOrderInfo() {
			this.$http
				.getMyorderinfo({
					order_num
				})
				.then((res) => {
					if (res.status == 200) {
						this.orderInfo = res.data;
					}
				});
		},

		sendMsg(data) {
			console.log('触发send', data);
			const _data = this.$u.deepClone(data);
			const { message_type } = _data.data;
			if (message_type === 'goods') {
				_data.data.message = 'goods' + '[' + _data.data.message + ']';
			}
			if (message_type === 'orders') {
				_data.data.message = 'orders' + '[' + _data.data.message + ']';
			}
			uni.sendSocketMessage({
				data: JSON.stringify({
					..._data
				}),
				success: () => {
					const { data: receiveData = {} } = data;
					const { message_type, message } = data.data;
					if (message_type === 'img') {
						receiveData.message = parseImgStr(message);
					} else if (message_type === 'goods') {
						receiveData.message = parseGoodsStr(message);
					} else if (message_type === 'orders') {
						receiveData.message = parseOrdersStr(message);
					} else {
						receiveData.message = $utils.generateRichTextNode(receiveData.message, receiveData.message_type);
					}
					this.msgList.push(receiveData);
					setTimeout(() => {
						this.scrollToBottom();
					}, 50);
				},
				fail: () => {}
			});
		},
		getMore() {
			if (!this.isMore) {
				uni.stopPullDownRefresh();
				return false;
			}
			this.loading = true;

			this.$http
				.getChatMsglist({
					page: this.page + 1,
					toid: this.toId
				})
				.then((res) => {
					console.log(res);
					this.loading = false;
					if (res.status === 200) {
						if (res.data.length) {
							let recordList = res.data.reverse();
							let newList = [];
							newList = recordList.map((item) => {
								item.to_headimgurl = item.fromid === uni.getStorageSync('token') ? item.to_headimgurl : item.from_headimgurl;
								item.message = $utils.generateRichTextNode(item.message, item.message_type);
								item.userType = item.fromid === uni.getStorageSync('token') ? 'customer' : 'home';

								return item;
							});
							this.isGetMore = true;
							this.$nextTick().then(() => {
								this.msgList.unshift(...newList);
								this.page = this.page + 1;

								uni.stopPullDownRefresh();
								this.$nextTick().then(() => {
									this.isGetMore = false;
								});
							});
						} else {
							uni.stopPullDownRefresh();
							this.isMore = false;
						}
					} else {
						console.log(242);
						this.$toast(res.message);
						uni.stopPullDownRefresh();
					}
				})
				.catch(() => {
					uni.stopPullDownRefresh();
				});
		},

		onShowEmoji(val, emojiStr) {
			if (val) {
				this.showEoji = false;
				this.focus = true;
			} else {
				uni.hideKeyboard();
				setTimeout(() => {
					this.showEoji = true;
					this.focus = false;
				}, 300);
			}
		},

		hideKeyboard() {
			this.showEoji = false;
			uni.hideKeyboard();
		},

		updataVal(val) {
			this.inputValue = val;
		},

		onUpload() {
			this.showEoji = false;
			$utils.chooseImg().then((response) => {
				this.$loading(this.$t('上传中'));
				uni.uploadFile({
					url: this.$baseUrl + 'api/Common/uploadPic',
					filePath: response.tempFilePaths[0],
					formData: this.$http.returnCommonParams('api/Common/uploadPic', 'chat_message'),
					name: 'file',
					success: (res) => {
						const data = JSON.parse(res.data);
						if (data.status === 200) {
							uni.getImageInfo({
								src: response.tempFilePaths[0],
								success: (image) => {
									let width = 0,
										height = 0;
									if (image.width > 400) {
										width = uni.upx2px(400);
										height = uni.upx2px(image.height * (400 / image.width));
									} else {
										width = uni.upx2px(image.width);
										height = uni.upx2px(image.height);
									}

									let sendData = {
										type: 'say',
										data: {
											userType: 'customer',
											fromid: uni.getStorageSync('token'),
											toid: this.toUserId,
											message: `img[${data.data.full_path}]`,
											message_type: 'img',
											width: width,
											height: height
										}
									};

									this.$hideLoading();

									this.sendMsg(sendData);
								}
							});
						} else {
							this.$toast(data.mess);
						}
					},

					fail: (err) => {
						this.$hideLoading();
					}
				});
			});
		},

		getInputMessage(message) {
			let sendData = {
				type: 'say',
				data: {
					userType: 'customer',
					fromid: uni.getStorageSync('token'),
					toid: this.toUserId,
					message: message.content,
					message_type: 'text'
				}
			};
			if (sendData.data.fromid == sendData.data.toid) {
				this.$toast(this.$t('不能给自己发送消息'));
				return;
			}

			this.sendMsg(sendData);
			this.showEoji = false;
			this.inputValue = '';
		},

		//   发送商品
		sendGoods(goodsInfo) {
			const { id: goodsId, goods_name: goodsName = '', thumb_url: goodsThumb = '', zs_shop_price: shopPrice = '' } = goodsInfo;
			const goodsStr = {
				goodsId,
				goodsName,
				goodsThumb,
				shopPrice
			};
			let sendData = {
				type: 'say',
				data: {
					userType: 'customer',
					fromid: uni.getStorageSync('token'),
					toid: this.toUserId,
					message_type: 'goods',
					message: JSON.stringify(goodsStr)
				}
			};
			this.sendMsg(sendData);
			this.goodsFloatShow = false;
		},
		//   发送订单
		sendOrders(orderInfo) {
			const { order_id: orderId, goods_name: goodsName = '', thumb_url: goodsThumb = '', real_price: realPrice = '' } = orderInfo;
			const goodsStr = {
				orderId,
				order_num,
				goodsName,
				goodsThumb,
				realPrice
			};
			let sendData = {
				type: 'say',
				data: {
					userType: 'customer',
					fromid: uni.getStorageSync('token'),
					toid: this.toUserId,
					message_type: 'orders',
					message: JSON.stringify(goodsStr)
				}
			};
			this.sendMsg(sendData);
			this.ordersFloatShow = false;
		},
		scrollToBottom() {
			uni.pageScrollTo({
				scrollTop: 20000,
				duration: 100
			});
		},
		closeGoodsFloat() {
			this.goodsFloatShow = false;
		},
		closeOrdersFloat() {
			this.ordersFloatShow = false;
		}
	},

	onPullDownRefresh() {
		this.getMore();
	}
};
</script>

<style lang="scss" scoped>
.no-more {
	margin-top: 10upx;
	text-algin: center;
}

.tip {
	position: fixed;
	top: 118upx;
	left: 30upx;
	z-index: 100;
	width: 690upx;
	height: 217upx;
	padding: 22upx 30upx 0 30upx;
	background: #fff;
	color: #999;
	font-size: 26upx;

	.tip-title {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 10upx;

		i {
			color: #999;
			padding-left: 20upx;
		}

		h2 {
			font-size: 34upx;
			color: #333;
		}
	}

	span {
		color: #f23333;
		font-size: 26upx;
		line-height: 1.4;
	}
}

.notice {
	display: flex;
	align-items: center;
	position: fixed;
	top: 0;
	width: 100%;
	height: 88upx;
	padding: 0 30upx;
	font-size: 24upx;
	background: #fff;
	color: #999;
	z-index: 100;

	image {
		width: 30upx;
		height: 30upx;
		padding-right: 6upx;
	}
}

.gift-btn {
	bottom: 200upx;
}

.chat {
	min-height: 100%;
	background: #f4f4f4;

	& > div {
		min-height: 100%;
		height: 100%;
	}

	.active {
		padding-top: 0 !important;
	}

	.content {
		height: auto;
		padding-bottom: 110upx;
		background: #f4f4f4;
	}

	.chat-footer {
		position: fixed;
		width: 100%;
		height: 110upx;
		left: 0upx;
		bottom: 0upx;
	}

	#bottom {
		padding-bottom: 20upx;
	}
}

.goods-float {
	position: fixed;
	bottom: 130rpx;
	background-color: #fff;
	border-radius: 14rpx;
	width: 95%;
	margin: 0 auto;
	left: 50%;
	transform: translateX(-50%);
	padding: 14rpx;
	display: flex;
	justify-content: space-between;

	&-thumble {
		flex-shrink: 0;
		margin-right: 10rpx;
	}

	&-sendBtn {
		align-self: flex-end;
	}

	&-close {
		position: absolute;
		right: 40rpx;
		top: 10rpx;
	}

	&-name {
		font-size: 24rpx;
		overflow: hidden;
		text-overflow: ellipsis;
		display: -webkit-box;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
		color: #333;
	}

	&-center {
		// width:380rpx;
		flex: 1;
		padding-right: 60rpx;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	&-price {
		color: #ff6262;
	}
}
</style>
